// routes/auth.js
const express = require('express');
const router = express.Router();
const User = require('../../models/vue-app/userPhone');

function generateVerificationCode() {
    return Math.floor(100000 + Math.random() * 900000).toString(); // 生成6位随机数
}

// 发送验证码
router.post('/send-code', async (req, res) => {
  const { phoneNumber } = req.body;
  const code = generateVerificationCode();
  const codeExpires = new Date(Date.now() + 10 * 60000); // 10分钟后过期

  try {
    let user = await User.findOne({ phoneNumber });
    if (!user) {
      user = new User({ phoneNumber });
    }
    user.verificationCode = code;
    user.codeExpires = codeExpires;
    await user.save();

    // 在这里发送验证码到用户手机，假设通过短信服务
    console.log(`验证码 ${code} 已发送到 ${phoneNumber}`);

    res.status(200).send(user.verificationCode);
  } catch (error) {
    res.status(500).send('服务器错误');
  }
});

// 验证验证码
router.post('/verify-code', async (req, res) => {
  const { phoneNumber, code } = req.body;

  try {
    const user = await User.findOne({ phoneNumber });
    if (!user || user.verificationCode !== code || user.codeExpires < new Date()) {
      return res.status(400).send('验证码无效或已过期');
    }

    // 验证成功，清除验证码
    user.verificationCode = null;
    user.codeExpires = null;
    await user.save();

    res.status(200).send('登录成功');
  } catch (error) {
    res.status(500).send('服务器错误');
  }
});

module.exports = router;